package cn.wolfcode.crm.shiro.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MyRealm extends AuthorizingRealm {

    // 获取认证信息
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //模拟查询账户
        String username= "admin";String password = "123";

        // String principal = (String) authenticationToken.getPrincipal();//一样的道理
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        // 不一致返回null,账户不存在
        if (!token.getUsername().equals(username)) {
            return null;
        }
        // 如果用户名一致,返回真实信息,密码的校验交给shiro
        return new SimpleAuthenticationInfo(username,password,getName());
    }

    // 获取授权信息
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        //模拟从数据库中查询到用户对应的角色数据
        List<String> roles = new ArrayList<>();
        roles.addAll(Arrays.asList("role1","role2"));
        //此处我们就模拟从数据库中查询到用户的权限数据。通过用户--->角色---->权限
        List<String> permissions = new ArrayList<>();
        permissions.addAll(Arrays.asList("user:create","user:update","user:delete"));

        //创建授权对象
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //将角色信息封闭为AuthorizationInfo
        simpleAuthorizationInfo.addRoles(roles);
        //将权限信息封闭为AuthorizationInfo
        simpleAuthorizationInfo.addStringPermissions(permissions);

        //返回授权信息
        return simpleAuthorizationInfo;
    }
}
